package com.class05.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @ClassDescription:
 * @JdkVersion: 17
 * @Author: yxy
 * @Created: 2023/11/8 15:57
 */
@Configuration
@ComponentScan("com.class05")
@PropertySource("classpath:jdbc.properties")
//@EnableAspectJAutoProxy  开启aspectj注解支持
@EnableTransactionManagement //开启事务注解支持
public class JavaConfig {
    @Value("${class05.driver}")
    private String driver;
    @Value("${class05.url}")
    private String url;
    @Value("${class05.username}")
    private String username;
    @Value("${class05.password}")
    private String password;

    //    druid 连接池
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //    声明式事务对应事务管理器
    @Bean
    public TransactionManager transactionManager(DataSource dataSource) {
//        //内部要进行事务的操作，基于连接池
        DataSourceTransactionManager dataSourceTransactionManager =
                new DataSourceTransactionManager();
//        //需要连接池对象
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;

    }
}
